#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'py_code_docx'))

from markdown_to_pdf import MarkdownToPDFWriter, MarkdownHTMLParser
import markdown
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

def debug_markdown_flow():
    print("=== 调试 Markdown 转换流程 ===")
    
    # 测试文本
    test_text = "这是中文测试文本 Hello World"
    print(f"原始文本: {test_text}")
    print(f"文本类型: {type(test_text)}")
    print(f"文本编码: {test_text.encode('utf-8')}")
    
    # 1. 测试 Markdown 转换
    print("\n=== 步骤1: Markdown 转换 ===")
    md = markdown.Markdown(extensions=['codehilite', 'tables', 'toc'])
    html_content = md.convert(test_text)
    print(f"HTML 内容: {html_content}")
    print(f"HTML 类型: {type(html_content)}")
    
    # 2. 测试 MarkdownToPDFWriter 初始化
    print("\n=== 步骤2: PDFWriter 初始化 ===")
    writer = MarkdownToPDFWriter()
    print(f"字体名称: {writer.font_name}")
    print(f"normal_style 字体: {writer.normal_style.fontName}")
    
    # 3. 测试 HTML 解析器
    print("\n=== 步骤3: HTML 解析 ===")
    parser = MarkdownHTMLParser(writer)
    
    # 重写 _add_paragraph 方法来添加调试信息
    original_add_paragraph = parser._add_paragraph
    def debug_add_paragraph(self):
        print(f"  准备添加段落: '{self.current_text}'")
        print(f"  文本类型: {type(self.current_text)}")
        print(f"  文本长度: {len(self.current_text)}")
        if self.current_text:
            print(f"  文本字节: {self.current_text.encode('utf-8')}")
        print(f"  当前样式: {self.current_style.fontName}")
        return original_add_paragraph()
    
    parser._add_paragraph = debug_add_paragraph.__get__(parser, MarkdownHTMLParser)
    
    # 解析 HTML
    parser.feed(html_content)
    
    # 4. 生成测试 PDF
    print("\n=== 步骤4: 生成 PDF ===")
    doc = SimpleDocTemplate("debug_flow.pdf", pagesize=A4)
    
    if writer.story:
        print(f"Story 元素数量: {len(writer.story)}")
        for i, element in enumerate(writer.story):
            if hasattr(element, 'text'):
                print(f"  元素 {i}: {type(element).__name__} - {element.text[:50]}...")
            else:
                print(f"  元素 {i}: {type(element).__name__}")
        
        try:
            doc.build(writer.story)
            print("PDF 生成成功: debug_flow.pdf")
        except Exception as e:
            print(f"PDF 生成失败: {e}")
    else:
        print("Story 为空！")
    
    # 5. 直接测试字体
    print("\n=== 步骤5: 直接字体测试 ===")
    try:
        direct_style = ParagraphStyle(
            'DirectTest',
            fontName=writer.font_name,
            fontSize=12
        )
        direct_para = Paragraph(test_text, direct_style)
        
        direct_doc = SimpleDocTemplate("debug_direct.pdf", pagesize=A4)
        direct_doc.build([direct_para])
        print("直接字体测试成功: debug_direct.pdf")
    except Exception as e:
        print(f"直接字体测试失败: {e}")

if __name__ == '__main__':
    debug_markdown_flow()